package actors;

import models.TienePersona;
import models.users.Role;
import models.users.User;
import play.libs.Akka;
import scala.Tuple3;
import services.DAO;
import services.Mailer;
import services.PasswordHash;
import util.PermissionValidator;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;

public class UserCreator extends UntypedActor {
	public static final ActorRef instance = Akka.system().actorOf(
			new Props(UserCreator.class));

	@SuppressWarnings("unchecked")
	@Override
	public void onReceive(Object arg0) throws Exception {
		Tuple3<String, String, String> ac = (Tuple3<String, String, String>) arg0;

		Mailer.sendHtmlMail("Nombre de usuario y contraseña",
				views.html.mailUsernameAndPassword.apply(ac._1(), ac._2())
						.body(), ac._3());
	}

	public static void createUser(TienePersona c) {
		String username = PermissionValidator.generateUsername(c);
		String password = PermissionValidator.generatePassword(c);
		String email = c.getPersona().getEmail();
		Tuple3<String, String, String> t = new Tuple3<String, String, String>(
				username, password, email);
		User u = new User();
		u.setIdActor(c.getId());
		u.setUsername(username);
		u.setPassword(PasswordHash.createHash(password));
		u.setRole(Role.getRoleFromClass(c.getClass()));
		DAO.persist(u);
		DAO.flush();// Se hace flush para que si falla algo en el persist, no se
					// envie el e-mail
		instance.tell(t, instance);
	}
}
